#include "Date.h"

int Date::GetMonthDay(int year, int month)
{
	assert(year >= 0 && month < 13 && month>0);
	//开辟一个静态区间，用来解决不同月份的天数不同
	static int monthDayAraay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && isLeapYear(month))
	{
		return 29;
	}
	return monthDayAraay[month];
}

Date::Date(int year, int month, int day)
{
	if (year > 0 && month < 13 && month>0 && day > 0 && day <= GetMonthDay(year,month))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期不合翻！" << endl;
		exit(-1);
	}
}

bool Date::operator == (const Date & d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator < (const Date& d)
{
	if (_year < d._year
		|| (_year == d._year && _month < d._month)
		|| (_year == d._year && _month == d._month && _day < d._day)
		)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Date& Date::operator += (int day)
{
	if (day < 0)
	{
		return *this -= -day;
	}
	_day += day;
	while (_day>GetMonthDay(_year,_month))
	{
		_day -= GetMonthDay(_year, _month);
		_month++;
		if (_month > 12)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator + (int day)
{
	Date ret(*this);
	ret += day;
	return ret;
}

Date& Date::operator -= (int day)
{
	if (day < 0)
	{
		return *this += -day;
	}
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (_month == 0)
		{
			_month = 12;
			_year--;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

Date Date::operator - (int day)
{
	Date ret(*this);
	ret -= day;
	return ret;
}

int Date::operator-(const Date& d)
{
	int flag = 1;
	Date max = *this;//默认认为第一大 
	Date min = d;
	if (*this < d)
	{
		min = *this;
		max = d;
		flag = -1;
	}
	int n = 0;
	while (min != max)
	{
		++n;
		++min;
	}
	return n * flag;
}